<template>
  <view class="data">
    <div class="bg">
      <div class="card">
        <div class="img" ref="imgRef" @click="changeInfo"></div>
        <div class="right" @click="lookIndent">
          <div class="name">{{ name }}</div>
          <div class="bottomData">
            <div class="treeNum left">
              <div class="div">云树</div>
              <div class="gleen div">{{ tree_num || 0 }}</div>
              <span style="color: #ddd;margin-left: 1.5vw;">|</span>
            </div>
            <div class="treeNum">
              <div>公益助绿</div>
              <div class="gleen">￥{{ tree_total.toFixed(2) || 0 }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="cell">
      <nut-cell-group>
        <nut-cell title="助绿信息" is-link @click="lookIndent">
          <template #icon>
            <img :src="EcologyImg" alt="" width="20px" height="100%" />
          </template>
        </nut-cell>
        <nut-cell title="个人信息" is-link @click="changeInfo">
          <template #icon>
            <img :src="userInfoImg" alt="" width="20px" height="100%" />
          </template>
        </nut-cell>
        <nut-cell title="联系我们" is-link @click="contactWe">
          <template #icon>
            <img :src="callImg" alt="" width="20px" height="100%" />
          </template>
        </nut-cell>
      </nut-cell-group>
      <nut-dialog
        no-cancel-btn
        title="联系电话"
        :content="phone"
        v-model:visible="isShowContact"
      />
    </div>
    <!-- safe-area-inset-bottom -->
    <nut-tabbar v-model="store.active" @tab-switch="tabSwitch" bottom active-color="#4cae4f" placeholder>
      <nut-tabbar-item tab-title="首页">
        <template #icon="props">
          <img :src="props.active ? icon.home_green : icon.home_black" alt="" />
        </template>
      </nut-tabbar-item>
      <nut-tabbar-item tab-title="我的荣誉">
        <template #icon="props">
          <img :src="props.active ? icon.me_green : icon.me_black" alt="" />
        </template>
      </nut-tabbar-item>
    </nut-tabbar>
  </view>
</template>

<script>
// vue
import { ref } from "vue";
// taro
import Taro from "@tarojs/taro";
import { useDidShow } from "@tarojs/taro";

// 图片
import wxImg from "../../images/wx.jpg"; // 
import right from "../../assets/img/right.png";
import call from "../../assets/img/call.png";
import Ecology from "../../assets/img/tree.png";
import userInfo from "../../assets/img/userInfo.png";
// tabbar
import { useCounterStore } from '../../store/tabbar'
import home_black from "../../images/home_black.png";
import home_green from "../../images/home_green.png";
import me_black from "../../images/me_black.png";
import me_green from "../../images/me_green.png";
// info
import { useInfoStore } from '../../store/info'

export default {
  name: "ReInfo",
  components: {},
  setup() {
    // tabbar
    const store = useCounterStore()
    const infoStore = useInfoStore()
    const icon = {
      unactive: home_green,
      home_black: home_black,
      home_green: home_green,
      me_black: me_black,
      me_green: me_green
    }
    const tabSwitch = (item, index) => {
      store.tabSwitch(index)
      if(index == 0) {
        Taro.switchTab({
          url: "/pages/home/index",
        });
      }
    }

    // 图片
    const rightImg = ref(right);
    const callImg = ref(call);
    const EcologyImg = ref(Ecology);
    const userInfoImg = ref(userInfo);

    const isShowContact = ref(false); //弹出层

    // 统计
    const tree_num = ref(0); //总数
    const tree_total = ref(0); // 总金额
    const treeData = ref([]); //数据

    const imgRef = ref(null);
    // 微信图片
    const selectedImg = ref(
      Taro.getStorageSync("img") ||
        wxImg
    );
    // 微信昵称
    const name = ref(Taro.getStorageSync("nickName") || "微信用户");
    const phone = ref("0769-23665839");

    // 获取数据
    const getTreeData = () => {
      console.log(infoStore.info.last_tree_total,'last_tree_total');
      console.log(infoStore.info.tree_total,'tree_total');
      // console.log(infoStore.info.code,'tree_total');
      if(infoStore.info.code == 0 && infoStore.info.last_tree_total !== infoStore.info.tree_total) {
        var result = infoStore.info.data.reduce(
          function (accumulator, currentValue) {
            if (currentValue.type == 1) {
              accumulator.num += currentValue.donate_number; // 累加数量
            } else {
              accumulator.num += 0; // 累加数量
            }
            accumulator.total += Number(currentValue.donate_total); // 累加总额
            return accumulator;
          },
          { num: 0, total: 0 }
        ); // 初始值为 { num: 0, total: 0 }
        tree_num.value = result.num;
        tree_total.value = parseFloat(result.total.toFixed(2));
        return
      } else if (!Taro.getStorageSync("openid")) {
        // console.log(22);
        getOpenId()
      } else {
        // console.log(111);
        getTreeDataApi();
      }
    };
    // 获取数据
    const getTreeDataApi = () => {
      let val
      Taro.request({
        url:
          "https://tree-planting.dgsxczxcjh.org.cn/api" +
          "/planting/listDonateRecord",
        method: "POST",
        data: { openid_mp: Taro.getStorageSync("openid") },
        success: (res) => {
          // 统一处理code = 0
          if (res.data.code == 0) {
            // console.log(res.data, "res.data"); //
            treeData.value = res.data.data;
            // 存到仓库
            var result = treeData.value.reduce(
              function (accumulator, currentValue) {
                if (currentValue.type == 1) {
                  accumulator.num += currentValue.donate_number; // 累加数量
                } else {
                  accumulator.num += 0; // 累加数量
                }
                accumulator.total += Number(currentValue.donate_total); // 累加总额
                return accumulator;
              },
              { num: 0, total: 0 }
            ); // 初始值为 { num: 0, total: 0 }
            // 将本次的值
            const my_tree_total = parseFloat(result.total.toFixed(2))
            // 将存上次的值
            const last_tree_total = infoStore.info.tree_total ? 0 : null
            tree_num.value = result.num;
            tree_total.value = my_tree_total;
            infoStore.changeInfo({...res.data, tree_num: result.num, tree_total: my_tree_total, last_tree_total })
            val = true
          } else {
            console.log(res.data, "res.data"); //
          }
        },
        fail: (err) => {
          console.log(err, "err"); //
          val = false
          getOpenIdFn() // 校验是否修改openid
     
        },
      });
      return
    };

    // 
    const getOpenIdFn = () => {
       Taro.login({
        success(res) {
          if (res.code) {
            // console.log(res.code, "code");
             Taro.request({
                url: "https://tree-planting.dgsxczxcjh.org.cn/api" + "/base/WeChat/getMpOpenid",
                method: "POST",
                data: { js_code: res.code },
                success: (res) => {
                  // 统一处理code = 0
                const { data } = res.data.data;
                // console.log(data, 'data');
                const myRegisterForm = {
                  openid: data.openid,
                  sessionKey: data.session_key,
                };
                const openid =  Taro.getStorageSync("openid")
                if(data.openid != openid){
                  Taro.setStorageSync("openid", data.openid);
                  getTreeDataApi()
                }
              },
              fail: (err) => {
                console.log(err, 'err'); //
              },
              });
          }
        },
      });
    }

    const getOpenId = () => {
      // console.log("获取openid");
      Taro.login({
        success(res) {
          if (res.code) {
            // console.log(res.code, "code");
             Taro.request({
                url: "https://tree-planting.dgsxczxcjh.org.cn/api" + "/base/WeChat/getMpOpenid",
                method: "POST",
                data: { js_code: res.code },
                success: (res) => {
                  // 统一处理code = 0
                const { data } = res.data.data;
                console.log(data, 'data');
                const myRegisterForm = {
                  openid: data.openid,
                  sessionKey: data.session_key,
                };
                Taro.setStorageSync("openid", data.openid);
                Taro.setStorageSync("sessionKey", data.session_key);
                getTreeDataApi()
              },
              fail: (err) => {
                console.log(err, 'err'); //
                Taro.showToast({
                  title: '错误',
                  icon: 'none',
                  duration: 2000
                })
              },
              });
          }
        },
      });
    };

    // 联系方式
    const getContactUs = () => {
      if(infoStore.contactUs.code == 0) {
        phone.value = infoStore.contactUs.data[0].value
        return
      }
     Taro.request({
          url: "https://tree-planting.dgsxczxcjh.org.cn/api" + "/planting/contactUs",
          method: "POST",
          data: { identification: 'call' },
          success: (res) => {
            // 统一处理code = 0
          const { data } = res.data;
          phone.value = data[0].value
          infoStore.changeContact(res.data)
        },
        fail: (err) => {
          console.log(err, 'err'); //
        },
        });
    };

    // 使用 useDidShow 钩子替代 onShow 生命周期
    useDidShow(() => {
      // tabbar
      store.tabSwitch(1)
      getTreeData(); // 数据
      getContactUs() // 联系方式

      // 用户信息
      const imgUrl =
        Taro.getStorageSync("img") // 图片
      if(!imgUrl) {
        Taro.setStorageSync("img", wxImg)
      }
      imgRef.value.style.backgroundImage = `url('${imgUrl  ||
        wxImg}')`;
      name.value = Taro.getStorageSync("nickName") || "微信用户";  // 昵称
    });

    
    // 跳转
    const lookIndent = () => { // 查看助绿信息
      Taro.navigateTo({
        url: `/pages/indent/index`,
      });
    };
    const changeInfo = () => {  // 用户信息
      Taro.navigateTo({
        url: `/pages/changeInfo/index`,
      });
    };
    
    // 弹出层
    const contactWe = () => { // 联系方式
      isShowContact.value = true;
    };


    return {
      selectedImg,
      name,
      imgRef,
      treeData,
      tree_num,
      tree_total,
      rightImg,
      changeInfo,
      lookIndent,
      contactWe,
      callImg,
      EcologyImg,
      userInfoImg,
      isShowContact,
      getOpenId,
      getOpenIdFn,
      getTreeDataApi,
      phone,
      tabSwitch, //tabbar
      store, //tabbar
      icon, //tabbar
    };
  },
};
</script>

<style lang="scss">

.data {
  // background-color: #f6f6f6;
  width: 100vw;
  min-height: 100vh;
  background-color: #eee;
  background: linear-gradient(to bottom,   
    rgb(177, 234, 163) 0%,  
    rgb(194, 239, 183) 5%,  
    rgb(253, 255, 252) 10%,  
    rgb(237, 240, 245) 100% 
); 
// 253, 255, 252
// #edf0f5 
  .bg {
    width: 100vw;
    padding-top: 1vh;
    margin-bottom: 5vh;
    .card {
      display: flex;
      background-color: #fff;
      width: 88vw;
      // height: 9vh;
      border-radius: 4vw;
      padding: 2.5vh 2vw;
      margin-left: 4vw;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); /* 水平偏移量，垂直偏移量，模糊程度，阴影颜色 */
      .img {
        border: 1px solid #e6e6e6;
        margin-left: 2vw;
        width: 16vw;
        height: 16vw;
        border-radius: 50%;
        // background-image: url("../../images/wx.jpg");
        // background-color: #fcf;
        background-size: cover; /* 图片完全覆盖div区域 */
        background-position: center; /* 图片居中显示 */
      }
      .right {
        margin-left: 4vw;
        text-align: left;
        .name {
          margin-top: 1vh;
          margin-bottom: 1.2vh;
          font-weight: 600;
          font-size: 5vw;
        }
        .bottomData {
          display: flex;
          font-size: 4vw;
          .left {
            margin-right: 2vw;
          }
          .gleen {
            color: #4cae4f;
            margin-left: 1vw;
          }
          .treeNum {
            display: flex;
            align-items: center;
            line-height: 3vh;
            height: 3vh;
            .div {
              display: flex;
              align-items: center;
            }
          }
        }
      }
    }
  }
  .cell {
    text-align: left;
  }
}

</style>
